package com.yuwei.security;

import com.yuwei.bean.SysUser;
import com.yuwei.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 根据username、获取账号、密码、所有角色list，构建security User对象，并返回。
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        //根据用户名查询用户
        SysUser sysUser = sysUserService.selectByUsername(username);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在");
        }
        //将所有角色名称add到  List<GrantedAuthority> 中。
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (sysUser != null) {
            //获取该用户所有角色
            List<String> sysRoles = sysUserService.selectRolesByUser(sysUser.getId());
            // 声明用户角色
            sysRoles.forEach(sysRole -> {
                //security 默认匹配角色时，会加上：“ROLE_”
                //说明：如果将 List<String> permissions 添加到 List<GrantedAuthority> 中，适用于表设计为：用户、权限 直接绑定。
                //我们这里 mysql表设计为：用户、角色、权限，三者绑定示例代码
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+ sysRole);
                grantedAuthorities.add(grantedAuthority);
            });
        }
        //构建User，保存username、password、权限list--grantedAuthorities
//        return new User(sysUser.getUsername(), sysUser.getPassword(),false,false, false, false, grantedAuthorities);
        return new User(sysUser.getUsername(), sysUser.getPassword(), grantedAuthorities);
    }
}
